package educar.controllers;


import educar.gui.IView;
import educar.gui.admin.AddStudent;
import educar.idioma.Locale;

import educar.listeners.Utiles;
import educar.models.Student;
import educar.models.User;
import educar.models.userNotFound;

/**
 * Permite agregar un alumno
 */
public class AddStudentController implements IController {
	private AddStudent view;
	
	public void process(String model){
		if(null!=view) {
			/*obtengo datos y compruebo validez*/
			String name = view.getName();
			String lastName = view.getLastName();
			String dni = view.getDNI();
			String adress = view.getAdress();
			String tel = view.getTelNumber();
			String email = view.getEmail();
			String year = view.getYear();
			String month = view.getMonth();
			String day = view.getDay();
			String sex = view.getSex();
			String username = view.getUserName();			

			if(name.length()==0 ||lastName.length()==0 || dni.length()==0 || adress.length()==0 || tel.length()==0 || email.length()==0
					|| year.length()==0 || month.length()==0 || day.length()==0 || sex.length()==0 || username.length()==0) {
				view.presentWarning(Locale.EMPTY_FIELDS, Locale.ERROR);
				return;
			}
			/*comprueba que la fecha sea valida*/
			if(!(Utiles.isDate(year+"-"+month+"-"+day))){
				view.presentWarning(Locale.INVALID_DATE, Locale.ERROR);
				return;
			}
			/*comprueba que el email sea valido*/
			if(!(Utiles.isEmail(email))){
				view.presentWarning(Locale.INVALID_EMAIL, Locale.ERROR);
				return;
			}
			else {
				/*intento crear el alumno*/
				Student newstudent = null;
				try {
					newstudent = new Student("0",dni,name,lastName,User.getUserByUsername(username),sex,adress,tel,email,year+"-"+month+"-"+day);
				} catch (userNotFound e1) {
					view.presentWarning(Locale.USER_NOT_FOUND,Locale.ERROR);
					e1.printStackTrace();
				} 
				try {
					boolean result = newstudent.save();
					if (!result) {
						view.presentWarning(Locale.DNI_USED, Locale.ERROR);
					}
					else {
						view.present(Locale.STUDENT+" "+Locale.SAVED);
						view.close();
					}
				} catch (NumberFormatException e) {
					view.presentWarning("Year is not Valid",Locale.ERROR);
				}
			}			
		}		
	}
	
	
	public void setView(IView view) {
		this.view = (AddStudent) view;		
	}	
}